from django.http import JsonResponse
from django.conf import settings
from app01 import models
import jwt


def logging_check(func):
    def wrap(request, *args, **kwargs):
        # 获取token, request.META.get('HTTTP_AUTHORIZATION')
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            result = {'code': 401, 'error': "未登录或登录已过期!"}
            return JsonResponse(result)
        # 校验token
        try:
            res = jwt.decode(token, settings.JWT_TOKEN_KEY, algorithms='HS256')
        except Exception as e:
            print(e)
            result = {'code': 401, 'error': "未登录或登录已过期!"}
            return JsonResponse(result)
        username = res['username']
        try:
            user = models.AdminProfile.objects.get(username=username)
        except Exception as e:
            result = {'code': 401, 'error': "未登录或登录已过期!"}
            return JsonResponse(result)
        request.myuser = user
        return func(request, *args, **kwargs)

    return wrap

def logging_check_user(func):
    def wrap(request, *args, **kwargs):
        # 获取token, request.META.get('HTTTP_AUTHORIZATION')
        token = request.META.get('HTTP_AUTHORIZATION')
        if not token:
            result = {'code': 401, 'error': "未登录或登录已过期!"}
            return JsonResponse(result)
        # 校验token
        try:
            res = jwt.decode(token, settings.JWT_TOKEN_KEY, algorithms='HS256')
        except Exception as e:
            print(e)
            result = {'code': 401, 'error': "未登录或登录已过期!"}
            return JsonResponse(result)
        username = res['username']
        try:
            user = models.UserProfile.objects.get(username=username)
        except Exception as e:
            result = {'code': 401, 'error': "未登录或登录已过期!"}
            return JsonResponse(result)
        request.myuser = user
        return func(request, *args, **kwargs)

    return wrap

